import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_model/home/module_detail_model.dart';
import 'package:xvideos/hj_page/home_business/special_topic_detail/specail_topics_detail_page.dart';
import 'package:xvideos/hj_page/home_business/widget/video_item.dart';
import 'package:xvideos/tools_base/banner/ads_grid_view_widget.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';

import '../home_cell_style/video_simple_cell_widget.dart';

/// 专题通用的头
class SectionHeader extends StatelessWidget {
  final AllSection? section;
  final bool isVideo;

  const SectionHeader({super.key, this.section, this.isVideo = true});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (isVideo) {
          Get.to(SpecailTopicsDetailPage(section), preventDuplicates: false);
        }
      },
      child: Row(
        children: [
          18.w.sizeBoxW,
          Expanded(
            child: Text(
              section?.sectionName ?? '',
              style: TextStyle(color: Colors.white, fontSize: 20.sp, fontWeight: FontWeight.w600),
            ),
          ),
          12.sizeBoxW,
          Text(
            '更多',
            style: TextStyle(color: Color(0x99FFFFFF), fontSize: 14, fontWeight: FontWeight.w400),
          ),
          4.sizeBoxW,
          Icon(
            Icons.arrow_forward_ios_rounded,
            size: 12,
            color: Color(0x99FFFFFF),
          ),
          18.w.sizeBoxW,
        ],
      ),
    );
  }
}

// OneLargeAndFourSmall    = iota // 0 一大四小
// FourHorizontalScreen           // 1 四宫格（横版）
// FourVerticalScreen             // 2 四宫格（竖版）
// SixHorizontalScreen            // 3 六宫格(横版)
// VerticalSixHorizontal          // 4 六宫格（竖版 ACG）
// VerticalEightHorizontal        // 5 八宫格（竖版 ACG）
// NineVerticalScreen             // 6 九宫格(竖版 ACG)
// HList                          // 7  列表(横版)
// VListScroll                    // 8 竖屏列表横滑动(ACG)
// HScroll25                      // 9 2.5左右滑动(横屏)
// VScroll25

/// 处理不同showtype展示
class SpecialSubjectRender {
  static Widget findMatchedView<T extends Widget>(AllSection section, {bool isVideo = true}) {
    final showT = section.showType ?? -1;
    print('SpecialSubjectRender $showT   name ${section.sectionName}');
    switch (showT) {
      /// 一大四小
      case 0:
        final itemConfig = ItemRenderConfig(titleMaxLines: 1);
        final config = SectionRenderConfig(
          ratio: 191 / 174,
          spacingH: 10,
          spacingV: 14,
          crossAxisCount: 2,
          totalCount: 4,
          itemConfig: isVideo ? itemConfig : null,
        );
        return OneBigAndSmallHSection<T>(
          dataSource: isVideo ? section.allVideoInfo ?? [] : section.allMediaInfo ?? [],
          config: config,
        );

      /// 四宫格横 acg or video
      case 1:
        SectionRenderConfig config = SectionRenderConfig(ratio: 191 / 174, spacingH: 10, spacingV: 14, crossAxisCount: 2, totalCount: 4);
        return GridSection<T>(
          dataSource: isVideo ? section.allVideoInfo ?? [] : section.allMediaInfo ?? [],
          config: config,
        );

      /// 一大六小-横版
      case 2:
        final itemConfig = ItemRenderConfig(titleMaxLines: 1);
        final config = SectionRenderConfig(
          ratio: 191 / 174,
          spacingH: 10,
          spacingV: 14,
          crossAxisCount: 2,
          totalCount: 6,
          itemConfig: isVideo ? itemConfig : null,
        );
        return OneBigAndSmallHSection<T>(
          dataSource: isVideo ? section.allVideoInfo ?? [] : section.allMediaInfo ?? [],
          config: config,
        );

      /// 6宫格横
      case 3:
        SectionRenderConfig config = SectionRenderConfig(ratio: 191 / 174, spacingH: 10, spacingV: 14, crossAxisCount: 2, totalCount: 6);
        return GridSection<T>(
          dataSource: isVideo ? section.allVideoInfo ?? [] : section.allMediaInfo ?? [],
          config: config,
        );

      /// 6宫格竖
      case 4:
        SectionRenderConfig config = SectionRenderConfig(ratio: 126 / 244, spacingH: 7, spacingV: 14, crossAxisCount: 3, totalCount: 6);
        return GridSection<T>(
          dataSource: isVideo ? section.allVideoInfo ?? [] : section.allMediaInfo ?? [],
          config: config,
        );

      /// 9宫格
      case 5:
        SectionRenderConfig config = SectionRenderConfig(ratio: 126 / 244, spacingH: 7, spacingV: 14, crossAxisCount: 3, totalCount: 9);
        return GridSection<T>(
          dataSource: isVideo ? section.allVideoInfo ?? [] : section.allMediaInfo ?? [],
          config: config,
        );

      /// 列表横
      case 6:
        if (isVideo) {
          SectionRenderConfig config = SectionRenderConfig(height: 99.h);
          return VListSection<VideoHItem>(
            dataSource: isVideo ? section.allVideoInfo ?? [] : section.allMediaInfo ?? [],
            config: config,
            // config: config,
          );
        }
        return Container();

      /// 2.5 横
      case 8:
        SectionRenderConfig config = SectionRenderConfig(height: 165.h, spacingH: 7.w, spacingV: 14, crossAxisCount: 3);
        return TwoHalfSection<T>(
          dataSource: isVideo ? section.allVideoInfo ?? [] : section.allMediaInfo ?? [],
          config: config,
        );

      /// 横斑列表
      case 13:
      default:
        return SizedBox();
    }
  }
}

/// 单个专题
class SingleSectionVew<T extends Widget> extends StatelessWidget {
  const SingleSectionVew({super.key, required this.section, this.isVideo = true});

  final AllSection section;
  final bool isVideo;

  @override
  Widget build(BuildContext context) {
    // 过滤掉没有数据的
    final realDataSource = (isVideo ? section.allVideoInfo : section.allMediaInfo) ?? [];
    print('SingleSectionVew  ${section.showType}    datasource = ${realDataSource}');
    return section.adsInfoArr != null
        ? AdsGridViewWidget(
            35,
            isBigStyle: true,
            padding: EdgeInsets.fromLTRB(16, 0, 16, 10),
            aspectRatio: 363 / 151,
            adsArr: section.adsInfoArr,
          )
        : realDataSource.isEmpty
            ? SizedBox.shrink()
            : Column(
                children: [
                  SectionHeader(
                    section: section,
                    isVideo: isVideo,
                  ),
                  14.sizeBoxH,
                  SpecialSubjectRender.findMatchedView<T>(section, isVideo: isVideo),
                ],
              );
  }
}

class SectionRenderConfig {
  bool? verticalCover;
  double? height;

  /// 默认等宽登高 1
  double? ratio;

  /// 网格横间距
  double? spacingH;

  /// 网格纵间距
  double? spacingV;

  /// 默认一排三个
  int? crossAxisCount;
  int? totalCount;

  /// 针对一大四小优化
  ItemRenderConfig? itemConfig;

  SectionRenderConfig(
      {this.verticalCover, this.height, this.ratio, this.spacingH, this.spacingV, this.crossAxisCount, this.totalCount, this.itemConfig});
}

abstract class _SpecialSubjectView<T extends Widget> extends StatelessWidget {
  final SectionRenderConfig? config;

  _SpecialSubjectView({super.key, this.config});

  final EdgeInsets padding = EdgeInsets.only(left: 18.w, top: 0, right: 18.w, bottom: 26.h);

  Widget buildContent(BuildContext context);

  T instanceView<T>(dynamic data, {ItemRenderConfig? config}) {
    final type = T.toString();
    if (type == 'VideoHItem') {
      return VideoHItem(model: data) as T;
    }
    if (type == 'VideoSimpleCellWidget')
      return VideoSimpleCellWidget(
        videoModel: data,
        textLines: config?.titleMaxLines ?? 2,
      ) as T;

    throw '$type 没有找到该类型';
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: padding,
      child: buildContent(context),
    );
  }
}

/// 垂直横向滚动
class HScrollListSection<T extends Widget> extends _SpecialSubjectView {
  final List dataSource;

  @override
  EdgeInsets get padding => super.padding.copyWith(right: 0);

  HScrollListSection({super.key, super.config, required this.dataSource});

  @override
  Widget buildContent(BuildContext context) {
    return GridView.builder(
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, crossAxisSpacing: 14.h, mainAxisSpacing: 30.w, childAspectRatio: 100 / 260),
      scrollDirection: Axis.horizontal,
      itemCount: dataSource.length,
      itemBuilder: (BuildContext context, int index) {
        return instanceView<T>(dataSource[index]);
      },
    );
  }
}

/// 垂直滑动
class VListSection<T extends Widget> extends _SpecialSubjectView {
  final List dataSource;

  VListSection({super.key, super.config, required this.dataSource});

  @override
  Widget buildContent(BuildContext context) {
    return ListView.separated(
      itemCount: dataSource.length,
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      separatorBuilder: (_, __) => 14.sizeBoxH,
      itemBuilder: (BuildContext context, int index) {
        return SizedBox(
          width: double.infinity,
          height: config?.height ?? 99.h,
          child: instanceView<T>(dataSource[index]),
        );
      },
    );
  }
}

/// 网格专题 4、6、9、8等
class GridSection<T extends Widget> extends _SpecialSubjectView {
  final List dataSource;

  GridSection({super.key, super.config, required this.dataSource});

  @override
  Widget buildContent(BuildContext context) {
    if (dataSource.isEmpty) return SizedBox.shrink();
    return GridView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: config?.crossAxisCount ?? 3,
          childAspectRatio: config?.ratio ?? 1,
          mainAxisSpacing: config?.spacingV ?? 0,
          crossAxisSpacing: config?.spacingH ?? 0),
      itemCount: min(config?.totalCount ?? 0, dataSource.length),
      itemBuilder: (BuildContext context, int index) {
        return SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: instanceView<T>(dataSource[index]),
        );
      },
    );
  }
}

/// (一大几小横) 一大四小
class OneBigAndSmallHSection<T extends Widget> extends _SpecialSubjectView {
  final List dataSource;

  OneBigAndSmallHSection({super.key, super.config, required this.dataSource});

  @override
  Widget buildContent(BuildContext context) {
    if (dataSource.isEmpty) return SizedBox.shrink();
    return Column(
      children: [
        SizedBox(
          height: 268.h,
          width: double.infinity,
          child: instanceView<T>(dataSource[0], config: config?.itemConfig),
        ),
        14.h.sizeBoxH,
        GridView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: config?.ratio ?? 1,
              mainAxisSpacing: config?.spacingV ?? 0,
              crossAxisSpacing: config?.spacingH ?? 0),
          itemCount: min(config?.totalCount ?? 4, dataSource.sublist(1).length),
          itemBuilder: (BuildContext context, int index) {
            return SizedBox(
              width: double.infinity,
              height: double.infinity,
              child: instanceView<T>(dataSource[index + 1]),
            );
          },
        ),
      ],
    );
  }
}

/// 2.5 滑动
class TwoHalfSection<T extends Widget> extends _SpecialSubjectView {
  final List dataSource;

  @override
  EdgeInsets get padding => super.padding.copyWith(right: 0);
  final double style = 2.5;

  TwoHalfSection({super.key, required this.dataSource, super.config});

  @override
  Widget buildContent(BuildContext context) {
    return SizedBox(
      height: config?.height ?? 165,
      child: LayoutBuilder(
        builder: (_, cons) {
          final width = (cons.maxWidth - style.toInt() * (config?.spacingH ?? 0)) / style;
          return ListView.separated(
            separatorBuilder: (_, __) => (config?.spacingH ?? 0).sizeBoxW,
            scrollDirection: Axis.horizontal,
            itemCount: dataSource.length,
            itemBuilder: (BuildContext context, int index) {
              return SizedBox(
                width: width,
                height: double.infinity,
                child: instanceView<T>(dataSource[index]),
              );
            },
          );
        },
      ),
    );
  }
}
